﻿using Newtonsoft.Json;
using System.Collections.Concurrent;
using System.Collections.ObjectModel;
using System.IO;
using System.Windows;
using VideoTools.Commands;
using VideoTools.service;
using VideoTools.SubtitleEdit.Common;
using VideoTools.vo;
using TaskStatus = VideoTools.vo.TaskStatus;

namespace VideoTools.Tasks
{
    public class OcrSupSubtitleTaskQueueManager : NotifyPropertyBase
    {
        private static volatile OcrSupSubtitleTaskQueueManager _instance;
        private static readonly object SyncRoot = new object();

        public static OcrSupSubtitleTaskQueueManager Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (SyncRoot)
                    {
                        if (_instance == null)
                        {
                            _instance = new OcrSupSubtitleTaskQueueManager();
                        }
                    }
                }

                return _instance;
            }
        }
        private bool _StartOcr = false;
        public bool StartOcr
        {
            get => _StartOcr;
            set
            {
                SetProperty(ref _StartOcr, value);
                if(value)
                    StartProcessing(); // 当开始OCR时尝试启动新任务
            }
        }
        private OcrSupSubtitleTaskQueueManager() { }

        private readonly ObservableCollection<OcrSupSubtitleTaskItem> _tasks =
            new ObservableCollection<OcrSupSubtitleTaskItem>();
        public IReadOnlyCollection<OcrSupSubtitleTaskItem> Tasks => _tasks;

        private int _maxConcurrentTasks = 5;
        public int MaxConcurrentTasks
        {
            get => _maxConcurrentTasks;
            set
            {
                SetProperty(ref _maxConcurrentTasks, value);
                StartProcessing(); // 当并发数改变时尝试启动新任务
            }
        }
        private IList<OcrSupSubtitleTaskItem> _SelectedTasks = new List<OcrSupSubtitleTaskItem>();
        public IList<OcrSupSubtitleTaskItem> SelectedTasks
        {
            get { return _SelectedTasks; }
            set
            {
                SetProperty(ref _SelectedTasks ,value);
            }
        }
        public readonly ConcurrentDictionary<OcrSupSubtitleTaskItem, bool> _runningTasks =
            new ConcurrentDictionary<OcrSupSubtitleTaskItem, bool>();
        public int RunningTaskCount => _runningTasks.Count;
        public int TaskCount => _tasks.Count;
        public int CompletedTaskCount =>
            _tasks.Where(f => f.Status == TaskStatus.Completed).ToList().Count;

        public OcrSupSubtitleTaskItem AddTask(
            OcrSupSubtitleTaskItem taskItem, System.Windows.Controls.ListView listView,
            Action<OcrSupSubtitleTaskItem, System.Windows.Controls.ListView> taskAction
        )
        {
            var existingDownloads = _tasks
                .Where(d => d.Paragraph.StartTime.Equals(taskItem.Paragraph.StartTime) && d.Paragraph.EndTime.Equals(taskItem.Paragraph.EndTime))
                .FirstOrDefault();
            if (existingDownloads is not null)
                return null;

            taskItem.TaskAction = () =>
            {
                taskAction(taskItem,listView);
            };
            _tasks.Add(taskItem);
            OnPropertyChanged(nameof(RunningTaskCount));
            OnPropertyChanged(nameof(TaskCount));
            OnPropertyChanged(nameof(CompletedTaskCount));
            //StartProcessing();
            return taskItem;
            //StartProcessing();
        }

        public void StartProcessing()
        {
            // 计算可以启动的新任务数量
            int availableSlots = MaxConcurrentTasks - _runningTasks.Count;
            //if(availableSlots < 0)
            //{

            //}
            if (availableSlots > MaxConcurrentTasks)
            {
                availableSlots = MaxConcurrentTasks;
            }
            for (int i = 0; i < availableSlots; i++)
            {
                var nextTask = _tasks.FirstOrDefault(t => t.Status == TaskStatus.Pending);
                if (nextTask == null)
                    break;

                StartTask(nextTask);
            }
        }

        private void StartTask(OcrSupSubtitleTaskItem task)
        {
            task.Status = TaskStatus.Running;
            _runningTasks[task] = true;
            OnPropertyChanged(nameof(RunningTaskCount));

            try
            {
                Task.Run(async () =>
                {
                    //task.Process();
                    task.TaskAction?.Invoke();
                    _runningTasks.TryRemove(task, out _);
                    OnPropertyChanged(nameof(RunningTaskCount));
                    OnPropertyChanged(nameof(TaskCount));
                    OnPropertyChanged(nameof(CompletedTaskCount));

                    StartProcessing(); // 任务完成后尝试启动新任务
                    if (task.Status == vo.TaskStatus.Running)
                    {
                        task.Status = vo.TaskStatus.Completed;
                    }
                });
            }
            catch (OperationCanceledException)
            {
                task.Status = TaskStatus.Failed;
            }
            catch
            {
                task.Status = TaskStatus.Failed;
            }
            finally { }
        }

        public void ClearAllTask()
        {
            _tasks.Clear();
        }
    }
}
